<?php


namespace catchAdmin\project\controller;

use app\common\business\Project;
use app\common\business\Question;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\Follow;
use app\common\model\QuestionDetail;
use catchAdmin\project\request\AnswerRequest;
use catchAdmin\project\request\ProjectRequest;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;
use catcher\library\client\Response;
use MongoDB\BSON\ObjectId;
use think\exception\ValidateException;
use think\Request;
use app\common\model\FollowHistory;

class Answer extends CatchController
{
    private ?\app\common\business\Answer $domain = null;

    public function __construct()
    {

        $this->domain = new \app\common\business\Answer();
    }


    public function save(Request $request): \think\response\Json
    {
      
        $postData = $request->param();
        try {

            validate(AnswerRequest::class)->scene("create")->check($postData);
            $result = $this->domain->createAnswer($postData);
            return CatchResponse::success($result);
        } catch (ValidateException $exception) {
            throw new ValidateFailedException($exception->getMessage());
        }
    }

    /**
     * 开始答题
     */
    public function startAnswer(Request $request): \think\response\Json
    {
        $projectId = $request->param("projectId", "", "string");
        $hisId = $request->param("his_id", "", "string");
        $source = $request->param("source", "", "string");
        $answerId = $request->param("answer_id", "", "string");
        $questionInfo = (new Project())->getProjectInfo($projectId);

        if (empty($questionInfo)) {
            throw new FailedException("问卷不存在");
        }

        if ($answerId) {
            $answerInfo = $this->domain->getAnswerById($answerId);
        } else {
            $answerInfo = $this->domain->getAnswerInfo($projectId, $hisId);
        }

        if (!empty($answerInfo)) {
            if (!isset($answerInfo["startTime"]) || empty($answerInfo["startTime"])) {
                //更新答题时间
                ZhyxMongo::getInstance()->setCollection('answer')->updateOne(["_id" => new  ObjectId($answerInfo["_id"])], ['$set' => ["startTime" => time(), "status" => 1]]);
            }

            if (isset($answerInfo["follow_id"]) && $answerInfo["follow_id"] !== 0) {
                (new Follow())->saveData($answerInfo["follow_id"], ["status" => 1]);

            }
            if ((isset($answerInfo["follow_id"]) && $answerInfo["follow_id"] !== 0) || $answerInfo["is_auto"] === 1) {
                (new FollowHistory())->saveData($answerInfo["history_id"], ["status" => 1]);
            }
        } else {
            throw new FailedException("问卷不存在");
        }
        return CatchResponse::success(["id" => (string)$answerInfo["history_id"], "status" => 1]);

    }

    /**
     * 获取问卷数汇总
     * @return \think\response\Json
     */
    public function getQuestionnaireSummary(CatchRequest $catchRequest): \think\response\Json
    {
        $projectId = $catchRequest->param("projectId", "", "string");
        if (empty($projectId)) {
            throw new FailedException("请传入问卷ID");
        }
        $result = $this->domain->getSummary($projectId);
        return CatchResponse::success($result);
    }


    public function index(CatchRequest $catchRequest)
    {
    

        $result = $this->domain->getList();
        return CatchResponse::paginate($result);
    }


    public function read(Request $request, $id)
    {
        $answerInfo = $this->domain->getAnswerById($id);
        return CatchResponse::success($answerInfo);
    }

    public function getAnswerDetailByFollowId(Request $request, $id): \think\response\Json
    {
        $answerInfo = $this->domain->getAnswerByFollowId($id);
        return CatchResponse::success($answerInfo);
    }

    public function getAnswerStatistics(CatchRequest $request)
    {
        $questionId = $request->param("id", "", "string");
        $taskId = $request->param("task_id", "", "string");
        if (empty($questionId)) {
            throw new FailedException("问题id不能为空");
        }

        //根据id获取问题详情
        $questionInfo = (new QuestionDetail())->where("id", "=", $questionId)->find();
        if (empty($questionInfo)) {
            throw new FailedException("问题不存在");
        }
        //[['$match' => ['questionId' => '6327e0b1a237000016006c31']], ['$group' => ['_id' => '$label', 'name' => ['$first' => '$label'], 'count' => ['$sum' => 1]]]]
        $match = ['questionId' => $questionId];
        if (!empty($taskId)) {
            $match["task_id"] = new ObjectId($taskId);
        }

        $result = ZhyxMongo::getInstance()->setCollection("answer_detail")->aggregate([['$match' => $match], ['$group' => ['_id' => '$label', 'name' => ['$first' => '$label'], 'count' => ['$sum' => 1]]]]);
        $arr = [];
        foreach ($result as $k => $v) {
            $arr[] = $v;
        }

        return CatchResponse::success([
            "chart_type" => $questionInfo["chart_type"],
            "result" => $arr
        ]);
    }

    public function modChartType(CatchRequest $request)
    {
        $projectId = $request->param("id", "", "string");

        $chartType = $request->param("chart_type", "", "int");
        if (empty($projectId) || empty($chartType)) {
            throw new FailedException("参数不能为空");
        }
        $result = ZhyxMongo::getInstance()->setCollection("question_detail")->updateOne(["_id" => new ObjectId($projectId)], ['$set' => ['chart_type' => $chartType]]);

        return CatchResponse::success($result);


    }


}